from rest_framework import serializers
from shop import models
from drf_haystack.serializers import HaystackSerializer
from .search_indexes import courseIndex


class CourseSearchSerializer(HaystackSerializer):
    class Meta:
        index_classes = [courseIndex]
        fields = ["id", "title", "students"]


class nav(serializers.ModelSerializer):
    class Meta:
        model = models.nav
        fields = '__all__'


class categroy(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()

    def get_children(self, obj):
        # 递归实现所有的分类 都是以children的形式返回
        if obj.children.all():
            # 如果有孩子返回所有孩子的序列化信息  如果没有返回的是空数据
            return categroy(obj.children.all(), many=True).data
        else:
            return []

    class Meta:
        model = models.categroy
        fields = '__all__'


class categroywithoutchild(serializers.ModelSerializer):
    class Meta:
        model = models.categroy
        fields = ["id", "name"]


class course(serializers.ModelSerializer):
    class Meta:
        model = models.course
        fields = '__all__'


class chaptercourse(serializers.ModelSerializer):
    class Meta:
        model = models.course
        fields = ["id", "title"]


class teacher(serializers.ModelSerializer):
    class Meta:
        model = models.teacher
        fields = '__all__'


class coursedetail(serializers.ModelSerializer):
    teacher = teacher()
    category = categroywithoutchild()
    nav = nav()

    class Meta:
        model = models.course
        fields = '__all__'


class chapternode(serializers.ModelSerializer):
    class Meta:
        model = models.node
        fields = '__all__'


class chapter(serializers.ModelSerializer):
    course = chaptercourse()
    node = chapternode(many=True)

    class Meta:
        model = models.chapter
        fields = '__all__'


class node(serializers.ModelSerializer):
    chapter = chapter()

    class Meta:
        model = models.node
        fields = '__all__'
